package pers.lolicer.redtidelibrary

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import pers.lolicer.redtidelibrary.utils.FileUtils

class ReceiveActivity:ComponentActivity() {
    @SuppressLint("UnsafeIntentLaunch")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val context = this
        val intent = intent

        if(intent.action == Intent.ACTION_SEND){
            val contentUri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            saveBook(context, contentUri)
        }

        if(intent.action == Intent.ACTION_SEND_MULTIPLE){
            val contentUris = intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)
            contentUris?.forEach{contentUri ->
                saveBook(context, contentUri)
            }
        }

        val jumpIntent = Intent(context, MainActivity::class.java)
        startActivity(jumpIntent)
    }
}

fun saveBook(context: Context, contentUri: Uri?){
    if(contentUri != null){
        context.grantUriPermission(context.packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
        context.contentResolver.takePersistableUriPermission(contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
//                    context.contentResolver.takePersistableUriPermission(contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

        FileUtils().saveBookToRoom(context, contentUri)
    }
    else{
        Log.e("分享文件出错：", "文件异常")
    }
}